package com.knife.tools;

import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Config
{
  public static String Debug = "false";
  public static String UploadFile;
  public static int PoolSize;
  public static String DRIVER;
  public static String UseCache = "false";
  public static String ValidationCode = "true";
  public static String TempPath="";
  public static String SiteDirectory="";
    private static final char LT_ENCODE[] = "&lt;".toCharArray();
	private static final char GT_ENCODE[] = "&gt;".toCharArray();
	private static final char QUOTE_ENCODE[] = "&quot;".toCharArray();
	private static final char ACUTE_ENCODE[] = "&acute;".toCharArray();
  private static Config singleton = new Config();

  public static Config getInstance()
  {
    return singleton; }

  public Config()
  {
     	Properties props = new Properties();
        InputStream in=null;
        try {
            in = getClass().getResourceAsStream("/SysConfig.properties");
            props.load(in);
            //wwwpath = props.getProperty("com.knife.blog.wwwpath");
            Debug = props.getProperty("DEBUG");
            DRIVER = props.getProperty("DRIVER");
            ValidationCode = props.getProperty("ValidationCode");
            TempPath = props.getProperty("TempPath");
            SiteDirectory = props.getProperty("com.knife.blog.wwwpath");
            in.close();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(in!=null){
                try{
                in.close();
                }catch(Exception e1){}
            }
        }
  }

  public static Date DateAdd(Date dtBegin, int seconds) throws Exception {
    Date dBefore = dtBegin;
    GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
    gc.setTime(dBefore);
    gc.add(13, seconds);
    dBefore = gc.getTime();
    return dBefore;
  }

  public static Date DateAdd(String flag, int num, Date dtBegin) throws Exception {
    Date dBefore = dtBegin;
    GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
    gc.setTime(dBefore);
    int field = 13;
    if (flag.equals("s")) field = 13;
    if (flag.equals("m")) field = 12;
    if (flag.equals("h")) field = 10;
    if (flag.equals("d")) field = 6;
    if (flag.equals("M")) field = 2;
    if (flag.equals("w")) field = 3;
    if (flag.equals("y")) field = 1;
    gc.add(field, num);
    dBefore = gc.getTime();
    return dBefore;
  }

  public static Date DateAddWorkDay(int flag, int num, Date dtBegin) throws Exception
  {
    Date dBefore = dtBegin;
    int i = 0;
    do {
      GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
      gc.setTime(dBefore);
      if ((i == 0) && (flag == 1)) gc.add(6, 1);
      if ((gc.get(7) != 7) && (gc.get(7) != 1)) ++i;
      gc.add(6, 1);
      dBefore = gc.getTime();

      gc = null; }
    while (i < num);
    return dBefore;
  }
  public static Date DateAddSecondes(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.SECOND, num);
	  return gc.getTime();	  
  }
  public static Date DateAddMinutes(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.MINUTE, num);
	  return gc.getTime();	  
  }
  public static Date DateAddHours(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.HOUR_OF_DAY, num);
	  return gc.getTime();	  
  }
  public static Date DateAddDays(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.DATE, num);
	  return gc.getTime();		  
  }
  public static Date DateAddMonths(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.MONTH, num);
	  return gc.getTime();		  
  }
  public static Date DateAddYears(int num,Date dtBegin){
	  GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
	  gc.setTime(dtBegin);
	  gc.add(Calendar.YEAR, num);
	  return gc.getTime();		  
  }
  public static int DateDiffWordDay(Date dtBegin, Date dtEnd) throws Exception {
    int retv = 0;
    Date dBefore = dtBegin;
    while (dtEnd.after(dBefore)) {
      GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
      gc.setTime(dBefore);

      if ((gc.get(7) != 7) && (gc.get(7) != 1)) ++retv;
      gc.add(6, 1);
      dBefore = gc.getTime();
      gc = null;
    }
    return retv; }

  public static int DateDiffWordDay(String dtBegin, String dtEnds) throws Exception {
    int retv = 0;
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date dBefore = dateFormat.parse(dtBegin);
    Date dtEnd = dateFormat.parse(dtEnds);
    while (dtEnd.after(dBefore)) {
      GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
      gc.setTime(dBefore);

      if ((gc.get(7) != 7) && (gc.get(7) != 1)) ++retv;
      gc.add(6, 1);
      dBefore = gc.getTime();
      gc = null;
    }
    return retv;
  }

  public static long DateDiff(Date dtBegin, Date dtEnd) throws Exception {
    long diff = dtBegin.getTime() - dtEnd.getTime();
    return (diff / 1000L);
  }

  public static String GetDateString(Date FieldValue) throws Exception {
    String sDate = "";
    Calendar cNow = Calendar.getInstance();
    Date aFieldValue = FieldValue;
    cNow.setTime(aFieldValue);
    sDate = sDate + cNow.get(1) + "-";
    if (1 + cNow.get(2) < 10) sDate = sDate + "0" + (1 + cNow.get(2)) + "-";
    else sDate = sDate + (1 + cNow.get(2)) + "-";
    if (cNow.get(5) < 10) sDate = sDate + "0" + cNow.get(5);
    else sDate = sDate + cNow.get(5);
    if (cNow.get(11) < 10) sDate = sDate + " 0" + cNow.get(11);
    else sDate = sDate + " " + cNow.get(11);
    if (cNow.get(12) < 10) sDate = sDate + ":0" + cNow.get(12);
    else sDate = sDate + ":" + cNow.get(12);
    if (cNow.get(13) < 10) sDate = sDate + ":0" + cNow.get(13);
    else sDate = sDate + ":" + cNow.get(13);
    return sDate;
  }

  public static String GetDateString2(Date FieldValue) throws Exception {
    String sDate = "";
    Calendar cNow = Calendar.getInstance();
    Date aFieldValue = FieldValue;
    cNow.setTime(aFieldValue);
    sDate = sDate + cNow.get(1);
    if (1 + cNow.get(2) < 10) sDate = sDate + "0" + (1 + cNow.get(2));
    else sDate = sDate + (1 + cNow.get(2));
    if (cNow.get(5) < 10) sDate = sDate + "0" + cNow.get(5);
    else sDate = sDate + cNow.get(5);
    return sDate;
  }

  public static String GetDateString3(Date FieldValue) throws Exception {
    String sDate = "";
    Calendar cNow = Calendar.getInstance();
    Date aFieldValue = FieldValue;
    cNow.setTime(aFieldValue);
    sDate = sDate + cNow.get(1) + "年";
    if (1 + cNow.get(2) < 10) sDate = sDate + "0" + (1 + cNow.get(2));
    else sDate = sDate + (1 + cNow.get(2));
    if (cNow.get(5) < 10) sDate = sDate + "0" + cNow.get(5);
    else sDate = sDate + "月" + cNow.get(5) + "日";
    return sDate; }

  public static String GetFieldString(Object FieldValue) throws Exception {
    String retStr = "";
    if (FieldValue == null) {
      retStr = "''";
    }
    else if (FieldValue.getClass().toString().equals("class java.lang.String")) {
      String aFieldValue = (String)FieldValue;
      retStr = "'" + aFieldValue.replaceAll("'", "''") + "'";
    }
    else if (FieldValue.getClass().toString().equals("class java.util.Date")) {
      String sDate = "";
      Calendar cNow = Calendar.getInstance();
      Date aFieldValue = (Date)FieldValue;
      cNow.setTime(aFieldValue);
      sDate = sDate + cNow.get(1) + "-";
      if (1 + cNow.get(2) < 10) sDate = sDate + "0" + (1 + cNow.get(2)) + "-";
      else sDate = sDate + (1 + cNow.get(2)) + "-";
      if (cNow.get(5) < 10) sDate = sDate + "0" + cNow.get(5);
      else sDate = sDate + cNow.get(5);
      if (cNow.get(11) < 10) sDate = sDate + " 0" + cNow.get(11);
      else sDate = sDate + " " + cNow.get(11);
      if (cNow.get(12) < 10) sDate = sDate + ":0" + cNow.get(12);
      else sDate = sDate + ":" + cNow.get(12);
      if (cNow.get(13) < 10) sDate = sDate + ":0" + cNow.get(13);
      else sDate = sDate + ":" + cNow.get(13);
      retStr = "'" + sDate + "'";
    }
    else if (FieldValue.getClass().toString().equals("class java.lang.Boolean")) {
      Boolean aFieldValue = (Boolean)FieldValue;
      if (aFieldValue.toString().equals("true")) retStr = "1";
      else retStr = "0";
    }

    return retStr;
  }

  public static String GetFieldString2(String FieldType, Object FieldValue, String DBType) throws Exception {
    String retStr = "";
    if (FieldValue == null) {
      retStr = "''";
    }
    else if ((FieldType.equalsIgnoreCase("char")) || (FieldType.equalsIgnoreCase("nchar")) || (FieldType.equalsIgnoreCase("varchar")) || (FieldType.equalsIgnoreCase("nvarchar")) || (FieldType.equalsIgnoreCase("varchar2"))) {
      String aFieldValue = (String)FieldValue;
      retStr = "'" + aFieldValue.replaceAll("'", "''") + "'";
    }
    else if ((FieldType.equalsIgnoreCase("datetime")) || (FieldType.equalsIgnoreCase("date")) || (FieldType.equalsIgnoreCase("timestamp"))) {
      String sDate = "";
      Calendar cNow = Calendar.getInstance();
      Date aFieldValue = (Date)FieldValue;
      cNow.setTime(aFieldValue);
      sDate = sDate + cNow.get(1) + "-";
      if (1 + cNow.get(2) < 10) sDate = sDate + "0" + (1 + cNow.get(2)) + "-";
      else sDate = sDate + (1 + cNow.get(2)) + "-";
      if (cNow.get(5) < 10) sDate = sDate + "0" + cNow.get(5);
      else sDate = sDate + cNow.get(5);
      if (cNow.get(11) < 10) sDate = sDate + " 0" + cNow.get(11);
      else sDate = sDate + " " + cNow.get(11);
      if (cNow.get(12) < 10) sDate = sDate + ":0" + cNow.get(12);
      else sDate = sDate + ":" + cNow.get(12);
      if (cNow.get(13) < 10) sDate = sDate + ":0" + cNow.get(13);
      else sDate = sDate + ":" + cNow.get(13);
      if (DBType.equalsIgnoreCase("MSSQL"))
        retStr = "CONVERT(DATETIME,'" + sDate + "')";
      else if ((DBType.equalsIgnoreCase("Oracle")) || (DBType.equalsIgnoreCase("DB2")))
        retStr = "TO_DATE('" + sDate + "','yyyy-mm-dd hh24:mi:ss')";
      else if (DBType.equalsIgnoreCase("MySQL"))
        retStr = "'" + sDate + "'";

    }
    else if (FieldType.equalsIgnoreCase("Boolean")) {
      Boolean aFieldValue = (Boolean)FieldValue;
      if (aFieldValue.toString().equals("true")) retStr = "1";
      else retStr = "0";
    } else if ((FieldType.equalsIgnoreCase("int")) || (FieldType.equalsIgnoreCase("number")) || (FieldType.equalsIgnoreCase("integer"))) {
      retStr = (String)FieldValue;
    } else {
      retStr = "''";
    }
    return retStr;
  }

  public static String DealNull(Object FieldValue) {
    if (FieldValue == null)
      return "";

    String retv = FieldValue.toString();
    if (retv.equalsIgnoreCase("null")) retv = "";
    return retv;
  }

  public static Date Now() throws Exception
  {
    return new Date(System.currentTimeMillis());
  }

  public static String getFileName(String fname)
    throws Exception
  {
    String retV = fname;
    if (fname.indexOf("/site") != -1) {
      String tmp = fname.substring(1);
      String[] tmps = tmp.split("/");
      String sitename = tmps[0];
      String siteid = sitename.substring(4);
      retV = retV.substring(5 + siteid.length());
    }
    return retV;
  }

  public static String Html2JS(String str)
  {
    String retV = "";
    if (str.equals("")) retV = "";
    StringBuffer jsstr = new StringBuffer();
    String cstr = str;
    cstr = cstr.replaceAll("\\\\", "\\\\\\\\");
    cstr = cstr.replaceAll("\\/", "\\\\/");
    cstr = cstr.replaceAll("\\\"", "\\\\\"");
    cstr = cstr.replaceAll("\\'", "\\\\'");
    String[] tmpstr = cstr.split("\\n");
    for (int i = 0; i < tmpstr.length; ++i)
      jsstr.append("document.writeln(\"").append(tmpstr[i]).append("\");\n");

    retV = jsstr.toString();
    return retV;
  }

  public static String Html2JS(String str, String obj) {
    String retV = "";
    if (str.equals("")) retV = "";
    String cstr = str;
    cstr = cstr.replaceAll("\\\\", "\\\\\\\\");
    cstr = cstr.replaceAll("\\/", "\\\\/");
    cstr = cstr.replaceAll("\\\"", "\\\\\"");
    cstr = cstr.replaceAll("\\'", "\\\\'");
    cstr = cstr.replaceAll("\\n", "\\\\\\\n");
    cstr = obj + ".innerHTML=\"" + cstr + "\";";
    retV = cstr;
    return retV;
  }

  public static String NoHtml(String msg) {
    String retv = "";
    try {
      Pattern pattern = Pattern.compile("<script[^>]*?>.*?</script>", 2);
      Matcher matcher = pattern.matcher(msg);
      retv = matcher.replaceAll("");
      pattern = Pattern.compile("<(.[^>]*)>", 2);
      retv = pattern.matcher(retv).replaceAll("");
      pattern = Pattern.compile("([\\r\\n])[\\s]+", 2);
      retv = pattern.matcher(retv).replaceAll("");
      pattern = Pattern.compile("-->", 2);
      retv = pattern.matcher(retv).replaceAll("");
      pattern = Pattern.compile("<!--.*", 2);
      retv = pattern.matcher(retv).replaceAll("");
      pattern = Pattern.compile("&(quot|#34);", 2);

      pattern = Pattern.compile("&(amp|#38);", 2);
      retv = pattern.matcher(retv).replaceAll("&");
      pattern = Pattern.compile("&(lt|#60);", 2);
      retv = pattern.matcher(retv).replaceAll("<");
      pattern = Pattern.compile("&(gt|#62);", 2);
      retv = pattern.matcher(retv).replaceAll(">");
      pattern = Pattern.compile("&(nbsp|#160);", 2);
      retv = pattern.matcher(retv).replaceAll("");

      pattern = Pattern.compile("&#(\\d+);", 2);
      retv = pattern.matcher(retv).replaceAll("");
      retv = retv.replaceAll(" ", "");
      retv = retv.replaceAll("<", "");
      retv = retv.replaceAll(">", "");
      retv = retv.replaceAll("/r", "");
      retv = retv.replaceAll("/n", "");
    } catch (Exception e) {
      retv = msg;
    }
    return retv;
  }

  public static String URIMap(String uri)
    throws Exception
  {
    uri = uri.trim();
    if (uri.equals(""))
      uri = "/";
    else if (!(uri.startsWith("/")))
      uri = "/" + uri;

    if (UploadFile.endsWith(File.separator))
      UploadFile = UploadFile.substring(0, UploadFile.length() - 1);
    if (File.separator.equals("\\"))
      uri = uri.replaceAll("/", "\\\\");
    return UploadFile + uri;
  }

  public static String GBK2Unicode(String s) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      if ((c >= 0) && (c <= 255)) {
        sb.append(c);
      } else {
        byte[] b;
        try {
          b = Character.toString(c).getBytes("utf-8");
        } catch (Exception ex) {
          System.out.println(ex);
          b = new byte[0];
        }
        for (int j = 0; j < b.length; ++j) {
          int k = b[j];
          if (k < 0) k += 256;
          sb.append("%" + 
            Integer.toHexString(k).toUpperCase());
        }
      }
    }
    return sb.toString();
  }

  public static String Unicode2GBK(String input)
  {
    StringBuffer sb = new StringBuffer();
    String[] Sinput = input.split("%u");
    if (Sinput.length <= 0)
      return "";

    String noUnicode = ""; String Unicode = "";
    for (int i = 0; i < Sinput.length; ++i) {
      String onestr = Sinput[i];
      if ((i == 0) && (onestr.indexOf("\"") >= 0)) {
        sb.append(onestr);
      }
      else if (onestr.length() >= 4) {
        Unicode = onestr.substring(0, 4);

        if (onestr.length() > 4)
          noUnicode = onestr.substring(4, onestr.length());
        else
          noUnicode = "";
        try
        {
          int cha = Integer.parseInt(Unicode, 16);

          short mp = (short)cha;

          char tm = (char)mp;
          sb.append(tm);
          sb.append(noUnicode);
        }
        catch (Exception e) {
          sb.append(onestr);
        }
      }
      else {
        sb.append(onestr);
      }
    }
    return sb.toString();
  }

  public static final String readUTF(byte[] data) throws Exception {
    int utflen = data.length;
    StringBuffer str = new StringBuffer(utflen);
    byte[] bytearr = data;

    int count = 0;
    while (count < utflen) {
      int char2;
      int c = bytearr[count] & 0xFF;
      switch (c >> 4)
      {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        ++count;
        str.append((char)c);
        break;
      case 12:
      case 13:
        count += 2;
        if (count > utflen)
          throw new Exception(
            "UTF Data Format Exception");

        char2 = bytearr[(count - 1)];
        if ((char2 & 0xC0) != 128)
          throw new Exception();

        str.append((char)((c & 0x1F) << 6 | char2 & 0x3F));
        break;
      case 14:
        count += 3;
        if (count > utflen)
          throw new Exception(
            "UTF Data Format Exception");

        char2 = bytearr[(count - 2)];
        int char3 = bytearr[(count - 1)];
        if (((char2 & 0xC0) != 128) || ((char3 & 0xC0) != 128))
          throw new Exception();

        str.append(
          (char)((c & 0xF) << 12 | 
          (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0));
        break;
      case 8:
      case 9:
      case 10:
      case 11:
      default:
        throw new Exception(
          "UTF Data Format Exception");
      }
    }

    return new String(str);
  }

  public static Date stringToDate(String time)
  {
    int tempPos = time.indexOf("AD");
    time = time.trim();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
    if (tempPos > -1) {
      time = time.substring(0, tempPos) + 
        "公元" + time.substring(tempPos + "AD".length());
      formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
    }
    tempPos = time.indexOf("-");
    if ((tempPos > -1) && (time.indexOf(" ") < 0)) {
      formatter = new SimpleDateFormat("yyyyMMddHHmmssZ");
    }
    else if ((time.indexOf("/") > -1) && (time.indexOf(" ") > -1)) {
      formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }
    else if ((time.indexOf("-") > -1) && (time.indexOf(" ") > -1)) {
      formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    else if (((time.indexOf("/") > -1) && (time.indexOf("am") > -1)) || (time.indexOf("pm") > -1)) {
      formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a");
    }
    else if (((time.indexOf("-") > -1) && (time.indexOf("am") > -1)) || (time.indexOf("pm") > -1))
      formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a");

    ParsePosition pos = new ParsePosition(0);
    Date ctime = formatter.parse(time, pos);
    return ctime; }

  public static String DateFormat(Date d) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String d_r = sdf.format(d);
    return d_r; 
    }
  
  public static boolean ProcessSqlStr(String sqlStr){
		boolean ps=false;
		if(sqlStr==null)return ps;
		String wrongStr = "'| and |exec|insert |select |delete |update | count|*|%| chr| mid|master |truncate |char |declare |;| or |+ | --";
		if(!("").equals(sqlStr)){
			String[] temp=wrongStr.split("\\|");
			for(int i=0;i<temp.length;i++){
				if(sqlStr.indexOf(" "+temp[i]+" ")!=-1){
					ps=true;
					break;
					}
			}
		}
		return ps;
	}
	/**
	 * @param total 总记录数
	 * @param PageSize 每页显示个数
	 * @return 总页数
	 */
	public static int TotalPage(int total,int PageSize){
		int retv =0;
		retv = (int)Math.ceil((total + PageSize-1) / PageSize);
		return(retv);
	}
	
	public static final String escapeHTMLTags(String in) {
		if (in == null)
			return null;
		int i = 0;
		int last = 0;
		char input[] = in.toCharArray();
		int len = input.length;
		StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
		for (; i < len; i++) {
			char ch = input[i];
			if (ch > '>')
				continue;
			if (ch == '<') {
				if (i > last)
					out.append(input, last, i - last);
				last = i + 1;
				out.append(LT_ENCODE);
				continue;
			}
			
			if (ch == '\'') {
				if (i > last)
					out.append(input, last, i - last);
				last = i + 1;
				out.append(ACUTE_ENCODE);
				continue;
			}
			
			
			
			if (ch == '>') {
				if (i > last)
					out.append(input, last, i - last);
				last = i + 1;
				out.append(GT_ENCODE);
				continue;
			}
			if (ch != '"')
				continue;
			if (i > last)
				out.append(input, last, i - last);
			last = i + 1;
			out.append(QUOTE_ENCODE);
		}

		if (last == 0)
			return in;
		if (i > last)
			out.append(input, last, i - last);
		return out.toString();
	}
	 public static void main(String[] a) {
		 Date d=Config.stringToDate("2010-01-13 09:50:23");
	      System.out.println(Config.DateAddYears(2, d));
	  }
}
